import _ from 'lodash';

export default {
  data() {
    return {
      show: false,
      pickerVal: '',
      filterVal: '',
      filterOption: []
    };
  },

  computed: {
    isNotData() {
      return this.filterOption.length === 0;
    },

    // 右边小图标
    rightIcon() {
      return (this.isValue && !this.canDo) ? 'close' : 'arrow-down';
    }
  },

  props: {
    filter: {
      type: Boolean,
      default: () => true
    },

    title: {
      type: String,
      default: () => ''
    }
  },

  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.pickerVal = val;
      }
    }
  },

  methods: {
    // clickRightIcon
    clickRightIcon() {
      const isClear = this.isValue;
      isClear && this.resetValue();
    },

    // 重置过滤
    resetFilter() {
      this.filterVal = '';
      this.inputFilter(this.filterVal);
    },

    closedPopup() {
      this.resetFilter();
    },

    // 打开弹窗
    openPicker() {
      if (!this.canDo) {
        // 远程数据
        if (this.remote) {
          this.fetchRemoteChoice();
        }
        this.show = true;
      }
    },

    // cancel
    handlerCancel() {
      this.show = false;
    },

    // 过滤
    inputFilter(value) {
      const _option = [];
      _.forEach(this.option, ({ field_label }, index) => {
        const isValue = field_label.toString()
          .toLowerCase().indexOf(value) > -1;
        isValue && _option.push(this.option[index]);
      });
      this.filterOption = _option;
    },

    // confirm
    handlerConfirm(val) {
      if (val) {
        const { field_value, field_label } = val;
        this.onChange(field_label || field_value);
      }

      this.show = false;
    }
  }
};
